package com.huajx.kit;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class FileKit {
	public static byte[] file2Byte(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			
			if(!file.exists()){
				System.err.println("未找到文件：" + filePath);
				return null;
			}
			
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] data = new byte[1024];
			int n;
			while ((n = fis.read(data)) != -1) {
				bos.write(data, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
				System.err.println("未找到文件：" + filePath);
				e.printStackTrace();
		} catch (IOException e) {
				System.err.println("文件转字节出错，文件：" + filePath);
		}
		return buffer;
	}
	
	public static String file2String(String filePath) {
		byte[] data = file2Byte(filePath);
		String result=null;
		
		try{
			result = new String(data, "UTF-8");
		}catch(Exception e){
		}
		return result;
	}
	
	public static void writeFile(String savePath, String content) {
		try {
			File file = new File(savePath);
			BufferedWriter output = new BufferedWriter(new FileWriter(file));
			output.write(content);
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void writeFile(File file, String content) {
		try {
			BufferedWriter output = new BufferedWriter(new FileWriter(file));
			output.write(content);
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
